package com.dong.algorithm.novice.linkedlist;

/**
 * 经典题目：用单链表结构实现栈
 * 时间复杂度O(1)
 *
 * @author by jiweidong on 2021/12/6.
 */
public class Arg02_LinkedListToStack {

    private static class Node<T> {
        private T value;
        private Node<T> next;

        public Node(T data) {
            this.value = data;
        }
    }

    public static class MyStack<V>{
        private Node<V> head;
        private int size;

        public MyStack (){
            this.head = null;
            this.size = 0;
        }

        public boolean isEmpty() {
            return this.size == 0;
        }

        public int size() {
            return this.size;
        }

        public void push(V value) {
            Node<V> cur = new Node<>(value);
            if (head == null) {
                head = cur;
            } else {
                cur.next = head;
                head = cur;
            }
            size++;
        }

        public V pop(){
            V ans = null;
            if (head != null) {
                ans = head.value;
                head = head.next;
                size--;
            }
            return ans;
        }

        public V peek() {
            return head != null ? head.value : null;
        }

    }


}
